package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.MyException;
import com.itheima.common.R;
import com.itheima.dto.page.MyPage;
import com.itheima.dto.yddUser.SysUserClone;
import com.itheima.dto.yddUser.SysUserInfo;
import com.itheima.entity.SysRole;
import com.itheima.entity.SysUser;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

@RequestMapping("/sys_user")
@RestController
@Slf4j
@CrossOrigin
public class SysUserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     *  用户列表分页查询
     * @param login_name 用户名
     * @param status 用户状态
     * @param phone 用户手机
     * @param page 当前页
     * @param limit 每页显示的条数
     * @return
     */
    @GetMapping("/list")
    public R<MyPage<SysUserInfo>> list(String login_name, Integer status, String phone, Integer page, Integer limit) {
        Page<SysUser> sysUserPage = new Page<>(page, limit);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(login_name != null && !login_name.equals(""), SysUser::getLoginName, login_name);
        wrapper.like(phone != null && !phone.equals(""), SysUser::getPhone, phone);
        wrapper.eq(status != null, SysUser::getStatus, status);
        userService.page(sysUserPage, wrapper);
        //设置MyPage的基本属性
        MyPage<SysUserInfo> myPage = new MyPage<>();
        //总条数
        myPage.setCount(sysUserPage.getTotal());
        //每页条数
        myPage.setPageSize(sysUserPage.getSize());
        //总页数
        myPage.setTotalPages((sysUserPage.getTotal() / sysUserPage.getSize() + 1));
        //当前页
        myPage.setCurrentPage(sysUserPage.getCurrent());
        List<SysUser> sysUserList = sysUserPage.getRecords();

        //创建 返回的数据 集合 对象为 userInfoDto
        List<SysUserInfo> userInfoList = new ArrayList<>();
        //循环 为每一个 userInfoDto 对象设置 roleName 角色名称
        for (SysUser sysUser : sysUserList) {
            SysUserInfo sysUserInfo = new SysUserInfo();
            //基本属性拷贝
            BeanUtils.copyProperties(sysUser, sysUserInfo);
            //根据RoleId 获得  sysRole 对象 获取他的 name 给userInfoDto 对象设置 roleName
            String roleId = sysUser.getRoleId();
            //截取 2-length() - 2 就是roleId
            String newRoleId = roleId.substring(2, roleId.length() - 2);
            String[] split = newRoleId.split(",");
            //SysRole sysRole = roleService.listByIds(split)
            String[] strings = new String[split.length];
            for (int i = 0; i < split.length; i++) {
                SysRole sysRole = roleService.getById(split[i]);
                strings[i] = sysRole.getName();
            }
            sysUserInfo.setRolename(strings);
            //将每次满属性的对象 放进集合
            userInfoList.add(sysUserInfo);
        }
        //将集合放进MyPage
        myPage.setData(userInfoList);
        return R.success(myPage);
    }

    /**
     *  删除用户
     * @param id 用户id
     * @return
     */
    @GetMapping("/del")
    public R<String> del(String id){
        // 根据页面传入的用户id获取用户信息
        SysUser sysUser = userService.getById(id);
        // 根据用户信息获取用户的角色id
        String roleId = sysUser.getRoleId();
        // 截取字符串获取新的角色id
        String newRoleId = roleId.substring(2, roleId.length() - 2);
        // 根据","切割字符串,获取该用户的roleId数组
        String[] roleIds = newRoleId.split(",");

        for (int i = 0; i < roleIds.length; i++) {
            SysRole sysRole = roleService.getById(roleIds[i]);
            if ("超级管理员".equals(sysRole.getName())) {
                throw new MyException("超级管理员不可被删除");
            }
        }
        userService.removeById(id);
        return R.success("操作成功!");
    }

    /**
     *  添加用户
     * @param sysUser 用户信息
     * @return
     */
    @PostMapping("/add")
    public R<String> save(@RequestBody SysUserClone sysUser){
        SysUser sysUser1 = getSysUser(sysUser);
        userService.save(sysUser1);
        return R.success("操作成功");
    }

    /**
     *  根据id查询用户信息(数据回显)
     * @param id 用户id
     * @return
     */
    @GetMapping("/rowInfo")
    public R<SysUserClone> getById(String id){
        SysUser sysUser = userService.getById(id);
        SysUserClone sysUserClone = new SysUserClone();
        BeanUtils.copyProperties(sysUser,sysUserClone,"roleId");
        String roleId = sysUser.getRoleId();
        String newRoleId = roleId.substring(2, roleId.length() - 2);
        String[] newRoleIds = newRoleId.split(",");
        ArrayList<String> roleIdList = new ArrayList<>(Arrays.asList(newRoleIds));
        sysUserClone.setRoleId(roleIdList);
        log.info("RoleId-->{}",sysUser.getRoleId());
        return R.success(sysUserClone);
    }

    /**
     *  修改用户信息
     * @param sysUser 用户信息
     * @return
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody SysUserClone sysUser){
        // 通过判断页面提交的参数中的phone属性是否有值来判断是修改用户信息还是修改用户状态
        if (StringUtils.isEmpty(sysUser.getPhone())) {
            // 如果phone为空,则是修改用户状态
            SysUser sysUser1 = userService.getById(sysUser);
            String roleId = sysUser1.getRoleId();
            String newRoleId = roleId.substring(2, roleId.length() - 2);

            String[] split = newRoleId.split(",");
            for (int i = 0; i < split.length; i++) {
                SysRole sysRole = roleService.getById(split[i]);
                if (sysRole.getName().equals("超级管理员")) {
                    throw new MyException("超级管理员不可被冻结");
                }
            }
            SysUser sysUser2 = new SysUser();
            sysUser2.setId(sysUser.getId());
            sysUser2.setStatus(sysUser.getStatus());
            userService.updateById(sysUser2);
        } else {
            // 如果不为空则是修改用户信息
            SysUser sysUser2 = getSysUser(sysUser);
            userService.updateById(sysUser2);
        }
        return R.success("修改成功!");
    }

    /**
     *  封装页面提交的参数信息
     * @param sysUser 页面提交的参数
     * @return
     */
    private SysUser getSysUser(@RequestBody SysUserClone sysUser) {
        SysUser sysUser2 = new SysUser();
        BeanUtils.copyProperties(sysUser, sysUser2, "roleId");
        StringJoiner joiner = new StringJoiner(",", "['", "']");
        for (String s : sysUser.getRoleId()) {
            joiner.add(s);
        }
        sysUser2.setRoleId(joiner.toString());

        String password = sysUser2.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser2.setPassword(password);
        return sysUser2;
    }
}
